﻿using MediatR;
using SheepCultivation.Common.Domain.main;
using SheepCultivation.Common.Domain.Week2;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;

namespace SheepCultivation.API.AddliCation.Tip_newspaper
{
    public class LambWeaningCreateHandler : IRequestHandler<LambWeaningCreateCommon, Result>
    {
        IBaseRepository<Lamb> LamdRepository;
        public LambWeaningCreateHandler(IBaseRepository<Lamb> lamdRepository)
        {
            LamdRepository = lamdRepository;
        }

        public async Task<Result> Handle(LambWeaningCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.error };
            try
            {
                var a= LamdRepository.GetAll().Where(x=>x.BreedingSheepArchiveId==request.BreedingSheepArchiveId).ToList();
                if (a.Count() == 0)
                {
                    var res = new Lamb()
                    {
                        BreedingSheepArchiveId = request.BreedingSheepArchiveId,
                        LambSex = request.LambSex,
                        BuildingId = 0,
                        ColumnsId = 0,
                        BuildingsEnter = request.BuildingsEnter,
                        ColumnsEnter = request.ColumnsEnter,
                        Heavy = request.Heavy,
                    };
                    LamdRepository.Add(res);
                }
                else
                {
                    foreach (var item in a)
                    {
                        item.BuildingId = LamdRepository.GetAll().Where(x => x.BreedingSheepArchiveId == item.BreedingSheepArchiveId).FirstOrDefault().BuildingsEnter;
                        item.ColumnsId = LamdRepository.GetAll().Where(x => x.BreedingSheepArchiveId == item.BreedingSheepArchiveId).FirstOrDefault().ColumnsEnter;
                        item.BreedingSheepArchiveId = request.BreedingSheepArchiveId;
                        item.LambSex = request.LambSex;
                        item.BuildingsEnter = request.BuildingsEnter;
                        item.ColumnsEnter = request.ColumnsEnter;
                        item.Heavy = request.Heavy;
                        LamdRepository.Update(item);
                    }
                }
                
                result.Code = (int)CommonEnumCode.success;
                result.Msg = "羔羊断奶新增成功";
            }
            catch (Exception ex)
            {

                result.Msg= "羔羊断奶新增失败";
            }
            return result;
        }
    }
}
